<%@ page import="com.devicemantra.coordinate.dataobjects.*,java.util.*,com.google.appengine.api.datastore.KeyFactory" %>
<html xmlns="http://www.w3.org/1999/xhtml">
 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Add Locations !</title>
 <head>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAZtqx8JxkReW-dJBlgM4IzBQ74rPPSn1VfJefnG1g1Sk4cx7G0BSXwSXOtS1XREDpMO1fhUYLdIfYSg"
            type="text/javascript"></script>
<script type="text/javascript" src="/js/xmlhelper.js"></script> 
<script type="text/javascript" src="/js/jquery.js"></script> 
<script type="text/javascript" src="/js/jquery.corner.js"></script> 
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script> 
<script type="text/javascript">
var map;
var lTime = 0;
var g_marker_manager;
var g_geoclient_coder;
var g_dragged_marker;

/* Added by Amith for poly feature */
var g_marker_arr = new Array();
var poly;
var count = 0;
var points = new Array();
var markers = new Array();
var icon_url ="http://labs.google.com/ridefinder/images/";
var tooltip;
var lineColor = "#0000af";
var fillColor = "#335599";
var lineWeight = 3;
var lineOpacity = .8;
var fillOpacity = .2;


function load() 
{
  if (GBrowserIsCompatible()) 
  {
    map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.enableGoogleBar();

	var center = new GLatLng(25.075648445630527,55.61279296875);
    map.setCenter(center,5);
    map.setZoom(8);

	g_geoclient_coder = new GClientGeocoder();
	g_geoclient_coder.setBaseCountryCode("ae");

    var mgrOptions = { borderPadding: 0, maxZoom: 15, trackMarkers: true };
	g_marker_manager = new MarkerManager(map,mgrOptions);
    // GEvent.addListener(map, "click", getAddress);
	GEvent.addListener(map, "click", leftBtnClick);
    
	// Add a div element for toolips
	 tooltip = document.createElement("div");
	 tooltip.className="tooltip";
	 map.getPane(G_MAP_MARKER_PANE).appendChild(tooltip);

  }
}

function initXMLHttpClient()
{
     var xmlhttp;
     try {
         // Mozilla / Safari / IE7
         xmlhttp = new XMLHttpRequest(); 
     } catch (e) {
          // IE
          var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
                                     'MSXML2.XMLHTTP.4.0',
                                     'MSXML2.XMLHTTP.3.0',
                                     'MSXML2.XMLHTTP',
                                     'Microsoft.XMLHTTP' );
        var success = false;
          for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {
              try {
                   xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
                      success = true;
                } catch (e) {}
          }
          if (!success) {
              throw new Error('Unable to create XMLHttpRequest.');
          }
     }
     return xmlhttp;
 }

function clearMarkers()
{
	g_marker_manager.clearMarkers();
}

function setLogo(pLogoPath)
{
	//alert("set marker " + pLogoPath);
	this.logoPath = pLogoPath;
}

function getValueFromNode(pNode)
{
	return (pNode[0].childNodes[0]).nodeValue; 
}

function cb_marker_clicked()
{
	//alert("click called now");
	//alert("Testing marker");
	/*alert(this.department);
	alert(this.frame_id); 	*/

	var lTabbedInfoWindow = [];
	lTabbedInfoWindow[1] = new GInfoWindowTab("Info","<form name=saveLoc method=POST action=/coordinate/php/save_loc_to_db.php>" +
							  	    "<table>" +
							  	    "<tr><td><img src=" + this.logo_path + "></td><td><font color=black><h4>Location Info </h4></font></td></tr>" + 
								    "<tr><td>Department</td><input type=text name=dept_name value=\"" + this.department  + "\"" +  " READONLY ></td>" +
								    "<tr><td>Emirate:</td><input type=text name=emirate value=\""+ this.emirate + "\"" +  " READONLY  \"></td>" +
								    "<tr><td>Address:</td><input type=text name=address value=\""+  this.address +  "\"" +  " READONLY  \"></td>" +  
								    "<tr><td>Latitude :</td><td><input type=text name=lat value="+ this.latitude +" READONLY  ></td></tr>" +
								    "<tr><td>Longitude :</td><td><input type=text name=lon value="+ this.longitude +" READONLY  ></td></tr>" +
								    "<tr><td>Location Description :</td><input type=text name=loc_desc value=\"" + this.description  + "\" READONLY  ></td>" +
								    "<tr><td><input type=hidden name=cframe_id value="+ this.frame_id  +">" +
		   							"<tr><td><div id=save_loc_status></div></td></tr>" +
								    "</table>" + "</form>"); 

	 lTabbedInfoWindow[0] = new GInfoWindowTab("Flash","<form name=saveMessage method=POST action=/coordinate/php/save_loc_to_db.php>" +
			  	    "<table>" +
			  	  "<tr><td><img src=" + this.logo_path + ">" +  
			  	  	"  Send a Message</td></tr>" + 
			  	    "<br><TEXTAREA name=message rows=3 cols=30></TEXTAREA></td></tr>" +
			  	    "<input type=hidden name=frame_id value="+ this.frame_id + ">" + 
			  	    "<tr><td><div id=msg_send_status></div></td></tr>" +
			  	    "<tr><td><br><input type=button value=Flash onClick=saveMessageToDb()></tr></td>" +  
			  	    "</table>" + "</form>"); 
		   // lTabbedInfoWindow[2] = new GInfoWindowTab("Modify","<font size=2 color=black>Save Info. </font>");
		      
	    	      //this.bindInfoWindowTabs(null);
	    	      //this.bindInfoWindowTabs(lTabbedInfoWindow);
	    	      this.openInfoWindowTabs(lTabbedInfoWindow);
				  return;
	   
}


function showFramesOnMap(pNodeList)
{
	  for(index =0; index < pNodeList.length ; index++)
	  {
		   var lTempNode = pNodeList[index];
		   var lNode = lTempNode.getElementsByTagName("CFrameId");
		   var lFrameId = getValueFromNode(lNode);
		   //alert(lFrameId);
		   lNode = lTempNode.getElementsByTagName("CLat");
		   var lLat = getValueFromNode(lNode);
		   //alert(lLat);
		   lNode = lTempNode.getElementsByTagName("CLong");
		   var lLong = getValueFromNode(lNode);
		   //alert(lLong);
		   lNode = lTempNode.getElementsByTagName("CEmirate");
		   var lEmirate = getValueFromNode(lNode);
		   //alert(lEmirate);
		   lNode = lTempNode.getElementsByTagName("CAddress");
		   var lAddress = getValueFromNode(lNode);
		   //alert(lAddress);
		   lNode = lTempNode.getElementsByTagName("CDepartment");
		   var lDept = getValueFromNode(lNode);
		   //alert(lDept);
		   lNode = lTempNode.getElementsByTagName("CDepartmentLogo");
		   var lDeptLogo = getValueFromNode(lNode);
		   //alert(lDeptLogo);
		   lNode = lTempNode.getElementsByTagName("CDescription");
		   var lDesc = getValueFromNode(lNode);
		   //alert(lDesc);
		   //alert(lFrameId + "" + lLat + " " + lLong + " " + lEmirate + " " + lAddress + " " + lDept + " " + lDesc);
		   /* Add the marked on the coordinates */
		   //lMarker = new GMarker(new GLatLng(lLat,lLong),{draggable: false});
		   //g_marker_manager.addMarker(lMarker,0,15);

		   var Icon = new GIcon();
		   Icon.image = lDeptLogo ;
		   Icon.iconSize = new GSize(21,31);
		   //Icon.shadow = "myshadow.png";
		   //Icon.shadowSize = new GSize(36, 34);
		   Icon.iconAnchor = new GPoint(5, 34);
		   Icon.infoWindowAnchor = new GPoint(5, 2); 

		   var lLatLong = new GLatLng(lLat,lLong);
		   var lMarker = new GMarker(lLatLong,{icon: Icon,draggable: false});
		   GMarker.prototype.setMarkerLogo = setLogo;
		   lMarker.setMarkerLogo(lDeptLogo);

		    
		   lMarker.frame_id = lFrameId;
		   lMarker.department = lDept;
		   lMarker.logo_path = lDeptLogo;
		   lMarker.latitude = lLat;
		   lMarker.longitude = lLong;
		   lMarker.emirate = lEmirate;
		   lMarker.address = lAddress;
		   lMarker.description = lDesc;
		   /* for Polygon feature - Amith */
		   lMarker.latLong = lLatLong;   
		    	
		   GEvent.addListener(lMarker,"click",cb_marker_clicked);
		   g_marker_manager.addMarker(lMarker,0,15);
		   /* for Polygon feature - Amith */
		   g_marker_arr.push(lMarker);
		   g_marker_manager.refresh(); 

		   
	}
}


function ShowFrames()
{
	var lSelBox = document.getElementById('dept_combo_box');
	var lSelDept = lSelBox.options[lSelBox.selectedIndex].value;
	var lSelBox1 = document.getElementById('emirate_combo_box');
	var lSelEmirate = lSelBox1.options[lSelBox1.selectedIndex].value;

	if(  (lSelDept == "NONE" ) || (  lSelEmirate == "NONE"))
	{
			alert("Please select from Department or Emirate");
	}

	//alert(lSelDept + " " + lSelEmirate);
	
    var httpGetReq = initXMLHttpClient();
    httpGetReq.onreadystatechange =function() 
    {
	   if (httpGetReq.readyState == 4) 
	   {
			if (httpGetReq.status==200)
			{
				//alert(httpGetReq.responseText);
				//alert(lIsShowAll);
				/* Clear all CFrames if the user does not want to see all of them */
				clearMarkers();

				var lXmlDoc = loadXmlText(httpGetReq.responseText);
		  		if(lXmlDoc)
		  		{
					var lNodeList = xmlDoc.getElementsByTagName("CLocation");
					//alert("node list length" + lNodeList.length);
					showFramesOnMap(lNodeList);
					document.getElementById('downloading_frames').innerHTML = "<br><font color=blue >Total " + lNodeList.length + " frames detected </font>";
					//alert("We have a " + lNodeList.length + " Node LIST !");
					show_marking_option();
	 			}
				else
				{
	                           alert('XML parsing FAILURE!');
		  		}
			}
	     }
	 }

     document.getElementById('downloading_frames').innerHTML = "<img height=32 width=32 src=\"/images/loading1.gif\"  alt=\"Processing\" />"; 
	 httpGetReq.open("GET","/GetFrames?dept_name="+lSelDept+"&emirate="+lSelEmirate,true);
	 httpGetReq.send(null); 
}

function SendClicked()
{
	var lSelBox = document.getElementById('dept_combo_box');
	var lSelDept = lSelBox.options[lSelBox.selectedIndex].value;
	var lSelBox1 = document.getElementById('emirate_combo_box');
	var lSelEmirate = lSelBox1.options[lSelBox1.selectedIndex].value;
	var lMessage = document.getElementById('message').value;
	/*alert(lSelDept);
	alert(lSelEmirate);
	alert(lMessage.length); */

	

	if( lSelDept == "NONE")
	{
		alert("Please select a Department");
		return;
	}
	
	if( lSelEmirate == "NONE")
	{
		alert("Please select an Emirate");
		return;
	}

	if( lMessage.length == 0)
	{
		alert("Please enter a message to be sent");
		return;
	}

	var httpPostReq = initXMLHttpClient();

	var url = "/BatchProcessMessage";
	var params = "message="+ lMessage +
			    "&dept_name="+ lSelDept + 
			    "&emirate_name=" + lSelEmirate;
	     
	httpPostReq.open("POST",url,true);

	httpPostReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpPostReq.setRequestHeader("Content-length", params.length);
	httpPostReq.setRequestHeader("Connection", "close");

	httpPostReq.onreadystatechange = function()
	{
    	if(httpPostReq.readyState == 4 && httpPostReq.status == 200)
    	{
	       	//alert(httpPostReq.responseText );
	       	document.getElementById('status').innerHTML = "<font color=green >Message sent</font>";     
    	}
    }
	document.getElementById('status').innerHTML = "<font color=blue >Sending message ...</font>";     
 	httpPostReq.send(params);
}
       
</script>

<style type="text/css">
</style>

<style type="text/css">
.box {
background-color :#E2E2E2;
margin:15px;
padding:5px;
}
</style> 

<script>
$(document).ready(
function () 
{
	//alert("markers rounding function called");
	$("div.box").corner(); 
	$("#map").corner("bevel 4px");
	$("#selected_box").corner();
	//$("#enable_marking").hide();
	//$("#map").fadeIn(3000);
	//$("#testbox").fadeIn(3000);
	
}
);
</script>

<script type="text/javascript">
/* Added by Amith for poly feature */
function leftBtnClick(overlay,point)
{
	//alert("leftBtnClick called  now ");
	if(point) 
	{
		  count++;

		if(count%2 != 0) 
		{

		  	// Light blue marker icons
		  	var icon = new GIcon();
		  	icon.image = "http://www.wolfpil.de/lightblue.png";
		  	addIcon(icon);
		 }
		 else 
		 {
		  	// Purple marker icons
		  	var icon = new GIcon();
		  	icon.image = icon_url +"mm_20_purple.png";
		  	addIcon(icon);
		 }

		  // Make markers draggable
		  var marker = new GMarker(point, {icon:icon, draggable:true, bouncy:false, dragCrossMove:true});
		  map.addOverlay(marker);
		  marker.content = count;
		  markers.push(marker);
		  marker.tooltip = "Point "+ count;

		  GEvent.addListener(marker, "mouseover", function() {
		   showTooltip(marker);
		  });

		  GEvent.addListener(marker, "mouseout", function() {
		   tooltip.style.display = "none";
		 });

		  // Drag listener
		  GEvent.addListener(marker, "drag", function() {
		   tooltip.style.display= "none";
		   drawOverlay();
		  });

		// Drag listener
		  GEvent.addListener(marker, "dragend", function() 
		  {
		   if(markers.length > 2)
		   {
					// alert("Calling re-calculate");
					countMarkersInside();
		   }
		   
		   drawOverlay();
		  });

		  

		  // Second click listener
		  GEvent.addListener(marker, "click", function() {
		  tooltip.style.display = "none";

		  // Find out which marker to remove
		  for(var n = 0; n < markers.length; n++) {
		   if(markers[n] == marker) {
		    map.removeOverlay(markers[n]);
		    break;
		   }
		  }

		  // Shorten array of markers and adjust counter
		  markers.splice(n, 1);
		  if(markers.length == 0) {
		    count = 0;
		  }
		   else {
		    count = markers[markers.length-1].content;
		    drawOverlay();
		  }

		  if(markers.length > 2)
			{
				// alert("Calling re-calculate");
				countMarkersInside();
			}	
		  
		  });
		 drawOverlay();
		 }

	if(markers.length > 2)
	{
		// alert("Calling re-calculate");
		countMarkersInside();
	}
	return true;
}

function addIcon(icon) 
{ // Add icon attributes

	 icon.shadow= icon_url + "mm_20_shadow.png";
	 icon.iconSize = new GSize(12, 20);
	 icon.shadowSize = new GSize(22, 20);
	 icon.iconAnchor = new GPoint(6, 20);
	 icon.infoWindowAnchor = new GPoint(5, 1);
}


function showTooltip(marker) 
{ // Display tooltips

	 tooltip.innerHTML = marker.tooltip;
	 tooltip.style.display = "block";

	 // Tooltip transparency specially for IE
	 if(typeof(tooltip.style.filter) == "string") {
	 tooltip.style.filter = "alpha(opacity:70)";
	 }

	 var currtype = map.getCurrentMapType().getProjection();
	 var point= currtype.fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	 var offset= currtype.fromLatLngToPixel(marker.getLatLng(),map.getZoom());
	 var anchor = marker.getIcon().iconAnchor;
	 var width = marker.getIcon().iconSize.width + 6;
	// var height = tooltip.clientHeight +18;
	 var height = 10;
	 var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y - height)); 
	 pos.apply(tooltip);
}

function drawOverlay()
{

	 if(poly)
	 { 
		 map.removeOverlay(poly); 
	 }

	 points.length = 0;

	for(i = 0; i < markers.length; i++) 
	{
	  	points.push(markers[i].getLatLng());
	}
	 
	 // Polygon mode
	 points.push(markers[0].getLatLng());
	 //poly = new GPolygon(points, lineColor, lineWeight, lineOpacity, fillColor, fillOpacity);
	 poly = new GPolygon(points, "#000000", 1, 1, "#336699", 0.3);
	 map.addOverlay(poly);
}


function isInside(point) 
{
    var j=0;
    var oddNodes = false;
    var x = point.lng();
    var y = point.lat();
    for (var i=0; i < poly.getVertexCount(); i++) {
      j++;
      if (j == poly.getVertexCount()) {j = 0;}
      if (((poly.getVertex(i).lat() < y) && (poly.getVertex(j).lat() >= y))
      || ((poly.getVertex(j).lat() < y) && (poly.getVertex(i).lat() >= y))) {
        if ( poly.getVertex(i).lng() + (y - poly.getVertex(i).lat())
        /  (poly.getVertex(j).lat()-poly.getVertex(i).lat())
        *  (poly.getVertex(j).lng() - poly.getVertex(i).lng())<x ) {
          oddNodes = !oddNodes
        }
      }
    }
    return oddNodes;
  }


function countMarkersInside()
{
	//alert("first " + document.getElementById('selected_frames').innerHTML);
	var lHtmlStr = "<table bgcolor=#9E9FA3 align=center>";
	lHtmlStr += "<thead><th>Check</th><th>Logo</th><th>Department Name</th><th>Emirate</th><th>Address</th><th>Description</th></thead>"
	var lCount = 0;
	for(i = 0; i < g_marker_arr.length; i++) 
	{
		//alert("The marker " + i + " is inside - " + isInside(g_marker_arr[i].latLong));
		if(isInside(g_marker_arr[i].latLong) == true)
		{
			lHtmlStr += "<tr>" + "<td bgcolor=white align=center><input type=checkbox checked=true /></td >" + "<td bgcolor=white align=center><img src=" + g_marker_arr[i].logo_path + " /></td> " + "<td bgcolor=white align=center><font face=\"times new roman\" color=brown size=1 ><b>" +  g_marker_arr[i].department + "</font></td>" +  "<td bgcolor=white align=center><font face=\"times new roman\" color=brown size=2 >" +  g_marker_arr[i].emirate + "</font></td>" + "<td align=center bgcolor=white width=100><font face=verdana color=black size=2 >" +  g_marker_arr[i].address + "</font></td>" + "<td align=center bgcolor=white width=100><font face=verdana color=black size=2 >" +  g_marker_arr[i].description + "</font></td>" +   "</tr>";
			lCount++;
			//alert("inside loop");
			//alert(lHtmlStr);
		}
	}
	//alert("exited loop");
	lHtmlStr += "</table>";
	var randomnumber=Math.floor(Math.random()*20)
	document.getElementById('selected_frames').innerHTML = lHtmlStr;
	document.getElementById('numframes_selected').innerHTML = "<font color=black size=3>Number of frames selected is " + (lCount ) + " [Contacts / SMS] : " + (lCount * 13) + " [Contacts / Email] :" + (lCount * 13) + "</font>";
}

function js_enable_marking()
{
	
	/*var lDivHtml = "<div style=\"clear:both;\"></div>" + 
	"<div class=box>" + 
	"<div id=\"numframes_selected\" style=\"left:20px\">No frames selected</div>" + 
	"<div id=\"selected_frames\" style=\"left:20px\"></div>" + "</div>";
	
	document.getElementById('selection_show').innerHTML = lDivHtml; */
}

function show_marking_option()
{
	//$("#enable_marking").fadeOut(3000);
}

</script>
</head>
<body onload="load()" onunload="GUnload()"  topmargin="0" leftmargin="0" >
<div class=box style="width: 740px; height:460px;">
<div id="map" style="position: relative;top: 5px; left: 5px;float:left;width: 730px; height:450px;border: 1px solid black;">
</div>
</div>

<div id="testbox" style="position:absolute; top:1px; right:0px">
<div class=box>
<table>
<tr>
<td><br> Select Departments / Emirates <br></br></td>
</tr>
<tr>
<td>
<select id="dept_combo_box" >
<option value="NONE" >Select a Department</option>
<option value="ALL">All the Departments</option>
<%
	List<CDepartment> lDeptList = CDepartmentFactory.getAllDepartments();
	for( int lCount = 0; lCount < lDeptList.size(); lCount++)
	{
		CDepartment lDept = lDeptList.get(lCount);
		out.print("<option value=\"" + lDept.getDepartmentName() + "\" >" + lDept.getDepartmentName() + " (" + lDept.getLocations().size()  + ")" +  "</option>");
	}	
%>
</select>
<p><b>IN</b></p>
<select id="emirate_combo_box" >
<option  value="NONE" >Select an Emirate</option>
<option value="ALL">All the Emirates</option>
<%
	List<CState> lStates = CStateFactory.getAllStates();
	for( int lCount = 0; lCount < lStates.size(); lCount++)
	{
		CState lState = lStates.get(lCount);
		out.print("<option value=\"" + lState.getName() + "\" >" + lState.getName() +   "</option>");
	}
	

%>
</select>
</td>
</tr>
<tr><td><input type=submit value="Show" onClick="ShowFrames()" ></input></td></tr>
<tr><td><div id="downloading_frames"></div></td></tr>
</table>
</div>


<div class=box style="top:1px; float:relative">
<p>Enter the message</p><b>
<TEXTAREA name=message id=message rows=4 cols=20></TEXTAREA>
<BR>
<input type=submit value="Send"  onClick="SendClicked()"></input>
<div id="status"></div>
</div>

<!-- Commented out temporarily  -->
<!--  <div id="enable_marking" style="position:relative; top:1px; "> 
<div class=box>
<input type=checkbox onClick="js_enable_marking()"> Enable marking</input>
</div>
</div> -->

</div>

<div style="clear:both;"></div>

<div class=box style="width:500;">
<div id="selected_box">
<div id="numframes_selected" style="left:40px; ">No frames selected</div>
<div id="selected_frames" style="left:20px"></div>
</div>
</div>
</body>
</html>

